package com.lance.answer.question_export;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import com.lance.answer.dto.Item;
import com.lance.answer.gui.answer.Question;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.gui.answer.gk.DealInfoUtil;
import com.lance.answer.util.MD5Utils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

import java.io.File;
import java.io.FileInputStream;
import java.time.Duration;
import java.util.*;

/**
 * <p>以老师的身份获取答案<p>
 *
 * @author : fengx
 * @since JDK8.0
 * <p>
 * <p>
 * 后面
 * 选择题、单元自测题、计分、分、自测、综合练习 都要获取
 * create by fengx on 2021/7/15 14:47
 */
public class GetAnswerByTeacher3Batch {

    public static void login(WebDriver driver, String userName, String pwd) {
        WebElement agreeButton = driver.findElement(By.id("RememberLogin"));
        agreeButton.click();

        WebElement userNameInput = driver.findElement(By.id("username"));
        userNameInput.clear();
        userNameInput.sendKeys(userName);

        WebElement passwordInput = driver.findElement(By.id("password"));
        passwordInput.clear();
        passwordInput.sendKeys(pwd);


        WebElement loginBtn = driver.findElement(By.name("button"));

        loginBtn.click();
    }

    public static void main(String[] args) throws Exception {
        ChromeDriver driver = Util.getDriver(null);
        String url = "http://thome.ouchn.cn/";
        driver.get(url);
        Thread.sleep(10000);
        //   String userName = "xj_zhishu15";
//        String userName = "xj_zhishu116";
//        String pwd = "zsxy123456WY";
        String userName = "zsxypy_1";
        String pwd = "zsxypy_1";
//        String userName = "zsxypy_1";
//        String pwd = "zsxypy_1";

        // start 2022-6-12 19:10
        // 统计学原理
        Map<String, String> SUBJECT = Maps.newHashMap();

        Set<String> names = Sets.newHashSet();
        for (File f1 : new File("D:\\newAnswerAll").listFiles()) {
            if (f1.isDirectory()) {
                continue;
            }
            String n = f1.getName();
            names.add(n.substring(0, n.length() - 5));
            System.err.println(n.substring(0, n.length() - 5));
        }

        for (String teacher : Lists.newArrayList(
                "刘",
                "刘庆",
                "宋柳萌",
                "朱晓玉",
                "李俊杰",
                "李明",
                "艾"
        )) {
            Map<String, List<String>> result = DealInfoUtil.countUserCourseInfo("libs//userCourseInfo//" + teacher);


            for (String key : result.keySet()) {
                if (!names.contains(key)) {
                    SUBJECT.put(key, key);

                    List<String> userNames = DealInfoUtil.countUserCourseInfo("libs//userCourseInfo//" + teacher).get(key);
                    if (userNames != null && userNames.size() > 0) {
                        System.out.println("key:" + key + "\t" + userNames.size());
                    }

                }
            }
        }

        System.err.println(JSON.toJSONString(SUBJECT.size()));


        login(driver, userName, pwd);

        Thread.sleep(1000);
        Util.switchToFirst(driver);

        // d://newAnswer//

        // key = subjectName value 做题链接集合
        Map<String, Set<String>> mapBySubjectName = Maps.newHashMap();
        for (File f1 : Objects.requireNonNull(new File("libs//courseUrlInfo").listFiles())) {
            Set<String> urlTaskSet = Sets.newHashSet();
//            if(f1.length()<100){
//                continue;
//            }
            String fileName = f1.getName();
            String subjectName = fileName.substring(0, fileName.length() - 4);
            List<String> urlInfoList = IOUtils.readLines(new FileInputStream(f1), "utf-8");
            for (String urlInfo : urlInfoList) {
                if (urlInfo.contains("quiz")) {
//                    if (urlInfo.contains("形考")
//                            || urlInfo.contains("作业")
//                            || urlInfo.contains("专题测验")
//                            || urlInfo.contains("专题检验")
//                            //  || urlInfo.contains("测试（")
//                            || urlInfo.contains("材料分析题（")
//                            || urlInfo.contains("综合记分作业")
//                            || urlInfo.contains("考核")
//                            || urlInfo.contains("测试")
//                            || urlInfo.contains("自测")
//                    ){
//                        String urlTask = urlInfo.split(",")[0];
//                        urlTaskSet.add(urlTask);
//                    }

                    String urlTask = urlInfo.split(",")[0];
                    urlTaskSet.add(urlTask);
                }

            }
            mapBySubjectName.put(subjectName, urlTaskSet);
        }


        //   for (String id : SUBJECT.keySet()) {


        for (String id : SUBJECT.keySet()) {
            System.err.println("id:" + id + " url:" + JSON.toJSONString(mapBySubjectName.get(id)));
            if (Strings.isNullOrEmpty(id)) {
                continue;
            }
            if (mapBySubjectName.get(id) == null) {
                continue;
            }
            if (SUBJECT.get(id).contains("机械CAD")) {
                continue;
            }
            try {
                driver.get("http://thome.ouchn.cn/");
                Thread.sleep(2000);
                String subjectName = SUBJECT.get(id);
                List<String> paths = new ArrayList<>();
                paths.addAll(mapBySubjectName.get(subjectName));
                driver.findElement(By.id("txtclassname")).clear();
                Thread.sleep(2000);
                driver.findElement(By.id("txtclassname")).sendKeys(subjectName);
                driver.findElement(By.className("btnblue_m")).click();
                Thread.sleep(5000);


                WebElement course = null;
                int code = 0;
                try {

                    WebElement we = Util.findByCssSelector(driver, "div[id='coursedesignList']");
                    if (we != null) {
                        if (we.getText().contains("暂无信息")) {
                            System.err.println("11111");
                            continue;
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                }
                System.err.println("2222222222");
                for (WebElement tr : new WebDriverWait(driver, Duration.ofSeconds(20)).until((ExpectedCondition<List<WebElement>>)
                        d -> d.findElements(By.tagName("tr")))) {
                    // 第一个TH是课程编号
//                    if (Util.findByTagName(tr, "td") == null) {
//                        continue;
//                    }
                    if (tr.findElements(By.className("bgcolor")).isEmpty()) {
                        System.err.println("33333333333333");
                        continue;
                    }
                    if (!subjectName.equals(tr.findElements(By.className("bgcolor")).get(1).getText().trim())) {
                        System.err.println("44444444444");
                        continue;
                    }
                    int tmp = Integer.parseInt(tr.findElements(By.className("bgcolor")).get(0).getText());
                    System.err.println("tmp:" + tmp);
                    if (tmp > code) {
                        code = tmp;
                        course = tr;
                    }

                }
                if (course != null) {
                    course.findElement(By.tagName("a")).click();
                } else {
                    continue;
                }
                Thread.sleep(5000);
                // ------------FIXME ----

                // 关闭其他页面，只留下当前课程页面
                Util.switchToFirst(driver);
                driver.close();
                Thread.sleep(2000);
                Util.switchToFirst(driver);
                List<Question> questions = Lists.newArrayList();
                // FIXME 如果标题相同就判断不出来了
                //   Set<String> titleSet = Sets.newHashSet();
                Map<String, String> questionAndAnswer = Maps.newHashMap();

                for (String urlTask : paths) {
                    try {
                        driver.get(urlTask);
                        Thread.sleep(5000);
                        // Util.switchToLast(driver);

                        System.err.println("z000000000000");
                        String text = driver.findElement(By.className("quizattemptcounts")).getText();

                        System.err.println("z111111111111111");
                        if (!text.contains("您同组内")) {
                            continue;
                        }


                        System.err.println("z22222222222222");
                        driver.findElement(By.className("quizattemptcounts")).findElement(By.tagName("a")).click();
                        Thread.sleep(5000);
                        // 回顾试答
                        // reviewlink
                        List<WebElement> infoList = new WebDriverWait(driver, Duration.ofSeconds(90)).until((ExpectedCondition<List<WebElement>>)
                                d -> d.findElements(By.cssSelector("a[class='reviewlink']")));

                        System.err.println("z33333333333");
                        boolean doubleGoBack = false;

                        int size = 0;
                        if (infoList.size() > 5) {
                            size = 5;
                        } else {
                            size = infoList.size();
                        }


                        //  for (int i = 0; i < infoList.size(); i++) {
                        for (int i = 0; i < size; i++) {
                            new WebDriverWait(driver, Duration.ofSeconds(90)).until((ExpectedCondition<List<WebElement>>)
                                    d -> d.findElements(By.cssSelector("a[class='reviewlink']"))).get(i).click();
                            // FIXME TODO 获取题目信息

                            Thread.sleep(5000);
                            for (WebElement wa : driver.findElements(By.tagName("a"))) {
                                if ("在一页上显示所有试题".equals(wa.getText())) {
                                    doubleGoBack = true;
                                    wa.click();
                                    Thread.sleep(5000);
                                    break;
                                }

                            }


                            for (WebElement singleSubject : Util.getSinglePageQuestionList(driver)) {

                                if (null == singleSubject) {
                                    continue;
                                }
                                String answerClass = singleSubject.getAttribute("class");
                                // informationitem  description description
                                if (Strings.isNullOrEmpty(answerClass)) {
                                    continue;
                                }
                                if (answerClass.contains("description") || answerClass.contains("informationitem")) {
                                    continue;
                                }
                                Question question = new Question();
                                question.setAnalyze("无");
                                question.setDifficult(1);
                                question.setGradeLevel(21);

                                String questionId = singleSubject.getAttribute("id");
                                // 这里的questionId是题目的ID
                                System.err.println("questionId:" + questionId);
                                WebElement contentElement = singleSubject.findElement(By.className("content"));

                                WebElement hiddenElement = singleSubject.
                                        findElement(By.cssSelector("input[type='hidden']"));
                                // 题干
                                String name = hiddenElement.getAttribute("name");
                                System.err.println("name:" + name);
                                // qtext
                                // 题目标题
                                String title = Util.getTitle(contentElement);
                                question.setTitle(title);
                                // FIXME
                                if (questionAndAnswer.containsKey(title)
                                        && !Strings.isNullOrEmpty(questionAndAnswer.get(title))
                                        && questionAndAnswer.get(title).length() > 8  // 进一步排除空的答案；
                                ) {
                                    continue;
                                }
                                // 题目提示 tip prompt
                                WebElement promptElement = Util.findByClassName(contentElement, "prompt");
                                if (null != promptElement) {
                                    System.err.println("promptElement:" + promptElement.getText());
                                }

                                WebElement answerElement = Util.findByClassName(contentElement, "answer");
                                String labelType = "";
                                List<Item> items = Lists.newArrayList();
                                items.clear();
                                if (null != answerElement) {
                                    // 找到每一个选项
                                    // 针对多选和单选和判断题
                                    for (WebElement singleAnswerElement : answerElement.
                                            findElements(By.cssSelector("div[class^='r0'],div[class^='r1']"))) {
                                        // 答案的序号 判断题没有序号 多选和单选有序号
                                        String answerNumber = "";
                                        WebElement numberElement = Util.findByClassName(singleAnswerElement, "answernumber");
                                        if (numberElement != null) {
                                            answerNumber = numberElement.getText();
                                        }
                                        // 每个答案的文本 p标签 =单选和多选 label标签=判断题
                                        String answerContent = Util.getAnswer(singleAnswerElement);
                                        // 找到单选框或复选框
                                        WebElement checkboxElement = singleAnswerElement.
                                                findElement(By.cssSelector("input[type='checkbox'],input[type='radio']"));
                                        labelType = checkboxElement.getAttribute("type");
                                        // 这里的ID是每个选项的ID
                                        // answerContent是每个选项的内容
                                        Item item = new Item();
                                        item.setPrefix(answerNumber);
                                        item.setContent(answerContent);
                                        if (Strings.isNullOrEmpty(answerContent)) {
                                            item.setPrefix(answerContent);
                                        }
                                        items.add(item);
                                    }
                                }


                                // 获取正确答案
                                WebElement rightAnswer = Util.findByClassName(singleSubject, "rightanswer");


                                String answer = null;
                                if (rightAnswer != null) {
                                    //     String[] correctArray = new String[]{rightAnswer.getText()};
                                    answer = Util.getAnswer(rightAnswer);
                                    String[] correctArray = new String[]{answer};
                                    question.setCorrectArray(correctArray);
                                }
                                if (rightAnswer == null) {
                                    rightAnswer = Util.findByClassName(singleSubject, "answer");
                                    if (rightAnswer != null) {
                                        answer = rightAnswer.getText();
                                        String[] correctArray = new String[]{answer};
                                        question.setCorrectArray(correctArray);
                                    }
                                }
                                if (question.getCorrectArray() == null || Strings.isNullOrEmpty(answer) || answer.length() < 5) {
                                    rightAnswer = Util.findByClassName(singleSubject, "generalfeedback");
                                    if (rightAnswer != null) {
                                        //  String[] correctArray = new String[]{Util.getAnswer(rightAnswer)};
                                        answer = rightAnswer.getText();
                                        String[] correctArray = new String[]{answer};
                                        question.setCorrectArray(correctArray);
                                    }
                                }

                                WebElement answerHistoryWe = Util.findByClassName(singleSubject, "generaltable");
                                if (answerHistoryWe != null) {
                                    //  String[] correctArray = new String[]{Util.getAnswer(rightAnswer)};
                                    String answerHistory = answerHistoryWe.getText();
                                    question.setAnswerHistory(answerHistory);
                                }


                                question.setItems(items);

                                //titleSet.add(question.getTitle());
                                questionAndAnswer.put(question.getTitle(), answer);

                                answerClass = singleSubject.getAttribute("class");
                                // 简单题que essay manualgraded notyetanswered
                                if (answerClass.contains("essay")) {
                                    // 等于选项的ID
                                    question.setQuestionType(5);
                                    question.setQuestionTypeDesc("简答题");
                                    question.setCorrect("简单题");
                                    questions.add(question);
                                }
                                // 判断题 que truefalse manualgraded notyetanswered  que truefalse deferredfeedback notyetanswered
                                if (answerClass.contains("truefalse")) {
                                    question.setQuestionType(3);
                                    question.setQuestionTypeDesc("判断题");
                                    questions.add(question);
                                }
                                // 填空题 que shortanswer deferredfeedback notyetanswered
                                if (answerClass.contains("shortanswer") || answerClass.contains("multianswer")) {
                                    // 等于选项的ID
                                    question.setQuestionType(4);
                                    question.setQuestionTypeDesc("填空题");
                                    questions.add(question);
                                }
                                // 多选|单选：que multichoice deferredfeedback notyetanswered
                                if (answerClass.contains("multichoice")) {
                                    if ("radio".equals(labelType)) {
                                        question.setQuestionType(1);
                                        question.setQuestionTypeDesc("单选题");
                                        questions.add(question);
                                    }
                                    if ("checkbox".equals(labelType)) {
                                        question.setQuestionType(2);
                                        question.setQuestionTypeDesc("多选题");
                                        questions.add(question);
                                    }
                                }

                                if (answerClass.contains("multianswer")) {
                                    questions.add(question);
                                }

                                if (answerClass.contains("ddwtos")) {
                                    // 等于选项的ID
                                    question.setQuestionType(10);
                                    question.setQuestionTypeDesc("ddwtos");
                                    questions.add(question);
                                    WebElement rightAnswer222 = Util.findByClassName(singleSubject, "rightanswer");
                                    if (rightAnswer != null) {
                                        //     String[] correctArray = new String[]{rightAnswer.getText()};
                                        String[] correctArray = new String[]{Util.dealContent(rightAnswer222.getText())};
                                        question.setCorrectArray(correctArray);
                                    }
                                }

                                if (answerClass.contains("que match deferredfeedback") // 匹配题目
                                ) {
                                    // 等于选项的ID
                                    WebElement tableWe = contentElement.findElement(By.cssSelector("table[class='answer']"));

                                    List<Item> items1 = Lists.newArrayList();
                                    for (WebElement trWe : tableWe.findElements(By.cssSelector("tr[class='r0'],tr[class='r1']"))) {
                                        Item item = new Item();
                                        item.setContent(trWe.findElement(By.cssSelector("td[class='text']")).getText());
                                        items1.add(item);
                                    }
                                    question.setItems(items1);
                                    question.setQuestionType(61);
                                    question.setQuestionTypeDesc("填空题");
                                    question.setCorrect("匹配题目");
                                    //    question.setCorrect(contentElement.findElement(By.cssSelector("div[clas='rightanswer']")).getText());
                                    questions.add(question);
                                }


                            }
                            Thread.sleep(5000);
                            driver.navigate().back();
                            Thread.sleep(2000);
                            if (doubleGoBack) {
                                driver.navigate().back();
                                Thread.sleep(2000);
                            }

                        }
                        Thread.sleep(2000);
                        //  driver.close();


                    } catch (Exception e) {

                    } finally {
                     try {
                         Util.switchToLast(driver);
                         Thread.sleep(2000);
                     }catch (Exception e2){

                     }
                    }
                }


                Collections.sort(questions);
                List<Map<String, Object>> answers = new ArrayList<>();
                for (Question question : questions) {

                    String title = question.getTitle();
                    title = Util.dealContent(title);
                    Map<String, Object> answerMap = new HashMap<>();
                    answerMap.put("questionType", question.getQuestionType());
                    answerMap.put("answerType", "click");

                    answerMap.put("questionTypeDesc", question.getQuestionTypeDesc());
                    answerMap.put("questionTitle", title);
                    answerMap.put("questionCode", MD5Utils.encode(subjectName + title));
                    answerMap.put("items", question.getItems());
                    answerMap.put("answers", question.getCorrectArray());
                    answerMap.put("answerHistory", question.getAnswerHistory());

                    answers.add(answerMap);
                }

                FileUtils.write(new File("d://newAnswerAll//" + subjectName + ".json"), JSONObject.toJSONString(answers, SerializerFeature.PrettyFormat), "utf-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        Thread.sleep(12000);
        driver.quit();
    }
}
